package org.w3.schools.ws;

import java.net.SocketTimeoutException;

import javax.xml.ws.WebServiceException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.NumberUtils;
import org.w3.schools.ws.v1_0.TempConvertSoap;

import com.exception.ws.BusinessException;
import com.exception.ws.TechnicalException;

@Component("tempConvertConnector")
public class TempConvertConnectorImpl implements TempConvertConnector {

	private static Logger log = LoggerFactory.getLogger(TempConvertConnectorImpl.class);

	@Autowired
	private TempConvertSoap wsTempConvertClientPortType;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.w3.schools.ws.TempConvertConnector#fahrenheitToCelsius(java.lang.
	 * String)
	 */
	public String fahrenheitToCelsius(String value) throws TechnicalException {
		
		NumberUtils.parseNumber(value, Double.class);
		
		String response = null;
		try {
			response = wsTempConvertClientPortType.fahrenheitToCelsius(value);
		} catch (WebServiceException e) {
			analyzeWsException(e);
		}
		return response;

	}

	/**
	 * @param e
	 * @throws TechnicalException
	 */
	protected void analyzeWsException(WebServiceException e) throws TechnicalException {
		if (ExceptionUtils.indexOfThrowable(e, SocketTimeoutException.class) != -1) {
			// receiveTimeout = Read timed out
			// connectionTimeout = connect timed out
			String stackTrace = ExceptionUtils.getFullStackTrace(e);
			if (StringUtils.indexOf(stackTrace, "Read timed out") != -1) {
				throw new TechnicalException("Socket timed out  : Read timed out", e);
			} else if (StringUtils.indexOf(stackTrace, "connect timed out") != -1) {
				throw new TechnicalException("Socket timed out : connect timed out", e);
			} else if (StringUtils.indexOf(stackTrace, "Connection timed out") != -1) {
				throw new TechnicalException("Socket timed out : connect timed out", e);
			} else {
				throw new TechnicalException("SOCKET TIMED OUT", e);
			}
		} else throw new TechnicalException("Cannot call server", e);
	}

	private void checkError(String response) throws BusinessException {
		log.info(" call ws return  this response: {}",response);
		if ("Error".contains(response))
			throw new BusinessException("Incorrect call");
	}

	public String celsiusToFahrenheit(String value) throws TechnicalException, BusinessException {
		String response = null;
		try {
			response = wsTempConvertClientPortType.celsiusToFahrenheit(value);
			checkError(response);
		} catch (WebServiceException e) {
			analyzeWsException(e);
		}
		return response;
	}
}
